from neutron import Plugin, execute, User, OS
from . import exts
# import os
import aiofiles
from fastapi import Form

from server import config

app = Plugin(__file__)

MAX_FILE_SIZE_BYTES = 1024*1024*16


@app.route.get("/file")
async def getfile(user: User, filepath: str, encoding="utf-8"):
    os = OS(user)
    if (user.demo):
        if (os.path.abspath(filepath).startswith(os.path.abspath("config"+os.sep))):
            return {
                "code": 1,
                "message": "演示模式下禁用本操作",
                "filetext": f"< 演示模式下禁用本操作 >",
                "readonly": True,
                "save": False,
                "language": "text",
                "filepath": filepath
            }
    # 读取文件
    try:
        if (await os.path.exists(filepath)):
            async with aiofiles.open(filepath, "r", encoding=encoding) as f:
                strs = await f.read(MAX_FILE_SIZE_BYTES)
            return {
                "code": 0,
                "message": "",
                "filetext": strs,
                "readonly": await os.access(filepath, os.W_OK) == False,
                "save": True,
                "language": exts.get_ext(filepath),
                "filepath": filepath
            }
        else:
            return {
                "code": 1,
                "message": "找不到文件",
                "filetext": f"< Error: 找不到文件 [{filepath}] >",
                "readonly": True,
                "save": False,
                "language": "text",
                "filepath": filepath
            }
    except UnicodeDecodeError:
        return {
            "code": 1,
            "message": "编码错误:"+encoding,
            "filetext": f"< Error: 编码错误 [{encoding}] >",
            "readonly": True,
            "save": False,
            "language": "text",
            "filepath": filepath
        }
    except PermissionError:
        return {
            "code": 1,
            "message": "权限不足",
            "filetext": "< Error: 权限不足 >",
            "readonly": True,
            "save": False,
            "language": "text",
            "filepath": filepath
        }
    except:
        return {
            "code": 1,
            "message": "未知错误",
            "filetext": "< Error: 未知错误 >",
            "readonly": True,
            "save": False,
            "language": "text",
            "filepath": filepath
        }


@app.route.post("/file")
async def writefile(user: User, filepath: str, encoding="utf-8", text=Form()):
    os = OS(user)
    if (user.demo):
        return {
            "code": 1,
            "message": "演示模式下禁用本操作"
        }
    # 写入文件
    try:
        async with os.open(filepath, "w", encoding=encoding) as f:
            await f.write(text)
        return {
            "code": 0,
            "message": ""
        }
    except UnicodeDecodeError:
        return {
            "code": 1,
            "message": "编码错误:"+encoding
        }
    except PermissionError:
        return {
            "code": 1,
            "message": "权限不足"
        }
    except:
        return {
            "code": 1,
            "message": "未知错误"
        }


def after_script():
    execute("filemanager", "bind_opener")("editor", "neutron.createIframeWin(\"\",\"/api/plugin/editor/iframe/index.html#{}\")",
                                          "/api/home/icon/editor/icon.png", "文本编辑")
    for i in exts.exts.keys():
        execute("filemanager", "bind_ext")(i, "editor")


app.after_run.append(after_script)
